<template>
	<div class="box outer-box" v-show="pageState === 'visible'">
		<Homeheader :hasList="true" :hasCart="true" :isHome="true">
		</Homeheader>
		<div class="main-container" ref="list" style="margin-top:60px;">
			<!-- production环境使用better-scroll滑动 -->
			<translate-main :lengths="1" :bounce="true" :showFoods="true" ref="translateMain" @scrollBottom="scrollBottom">
					<component 
						v-for="(item, index) in getRealComponentsList[0][1]" 
						v-sdrag="{componentName: item.componentName, handleType: 'sort', index}" 
						:is="item.componentName" 
						:key="index" 
						:config="item" 
						:data-id="item.id" 
						:dataList="dataStore[item.componentName][item.id]" 
						:part="1">
					</component>
					<HomeFooter v-if="flagfoot"></HomeFooter>
			</translate-main>
		</div>
		<add-cart-animate></add-cart-animate>
	</div>
</template>

<script>
	import Homeheader from "../header";
	import AddCartAnimate from "@/real-components/AddCartAnimate";
	import AnimateRefresh from "@/real-components/AnimateRefreshPull";
	import TabHead from "../../real-components/TabHead";
	import TranslateMain from "../../real-components/TranslateTest";	
	import HomeNotice from "../../real-components/HomeNotice/_index";
	import HomeCarousel from "../../real-components/HomeCarousel/_index";
	import UserCard from "../../real-components/UserCard/_index";
	import NewZone from "../../real-components/NewZone/_index";
	import ProductItemNew from "../../real-components/ProductItemNew/_index";
	import FeaturedGoodsNew from "../../real-components/FeaturedGoodsNew/_index";
	import FirstClassifyNew from "../../real-components/FirstClassifyNew/_index";
	import GuessYouLike from "../../real-components/GuessYouLike/_index"
	import HomeFooter from "../../real-components/HomeFooter";
	import ActivitiesTwoPro from "../../real-components/activitiesTwoPro/_index";
	import ActivitiesOnePro from "../../real-components/activitiesOnePro/_index";
	import ActivitiesNinePro from "../../real-components/activitiesNinePro/_index";
	import ActivitiesThreePic from "../../real-components/activitiesThreePic/_index";
	import Activitiesbanner from "../../real-components/activitiesbanner/_index";
	import ActivitieCoupons from "../../real-components/ActivitieCoupons/_index";
	import ActivitieCoupons2 from "../../real-components/ActivitieCoupons2/_index";
	import { mapGetters, mapMutations } from "vuex";	
	import axios from "axios";
	import ll from "./Loading";
	import initData, {baseComponentNames} from "../../utils/lxn/handleData";
	export default {
		name: "hello",
		data() {
			return {
				sessionIddata: "",
				storeCodedata: "",
				//优惠券列表
				couponsdata: [],
				//弹框广告数据
				advImg: "",
				advLink: "",
				adType: "",
                flagfresh:true,
				flagfoot:false,
				pageState: "visible",
				// dataStore: {
				// 	...baseComponentNames
				// }
			};
		},
		computed: {
			...mapGetters("xxy", {
				dataStore: "getDataStore"
			}),
			...mapGetters("gw", ["getRealComponentsList"]),
			//获取当前页面名称（包含虚拟页面）
			page() {
				return this.$store.getters["gw/getVirtualPageName"] ? this.$store.getters["gw/getVirtualPageName"] : "home";
			},
			// activeIndex() {
			// 	return this.$store.state.cjy.classifyIndex;
			// },
			classifyList() {
				return this.$store.getters["cjy/classifyData"];
			},
			scrollTop() {
				return this.$store.state.cjy.pagePosY;
			},
			//消息推送
			hasNotice() {
				return this.$store.state.xxy.hasNotice
			}
		},
		components: {
			AddCartAnimate,
			HomeCarousel,
			HomeNotice,
			HomeFooter,
			Homeheader,
			UserCard,
			NewZone,
			ProductItemNew,
			FeaturedGoodsNew,
			FirstClassifyNew,
			ActivitiesTwoPro,
			ActivitiesOnePro,
			ActivitiesNinePro,
			ActivitiesThreePic,
			Activitiesbanner,
			ActivitieCoupons,
			ActivitieCoupons2,
			GuessYouLike: () => ({
				component: new Promise((resolve) => {
					setTimeout(() => {
						resolve(
							import("../../real-components/GuessYouLike/_index"));
						PSEvent.trigger("initDom");
					}, 1000);
				}),
				loading: ll
			}),
			TranslateMain, // 左右滑动组件
			TabHead, // 头部tap栏
			AnimateRefresh
		},
		methods: {
			...mapMutations("xxy", ["sethomehid", "setpopupVisible", "setactivePic"]),
			//刷新页面
			refresh() {
				this.$nextTick(() => {
					this.$refs.translateMain && this.$refs.translateMain.refresh();
				});
			},
			//上拉加载
			scrollBottom() {
				PSEvent.trigger('scrollBottom')
				this.$refs.classifyList && this.$refs.classifyList[0] && this.$refs.classifyList[0].loadMore();
			    this.refresh()
			},
			//下拉刷新
			dataRefresh() {
				PSEvent.trigger(this.page)
				if(this.page === "home" && this.flagfresh) {
                    this.flagfresh = false
					this.getHomeData(true);
					this.$store.dispatch('cjy/queryNewClassifyList');
				}
				setTimeout(() => {
                    this.flagfresh = true
					window.PSEvent.trigger('pageLoadedOver')
				}, 1200)
			},
			//获取门店信息和sessionId
			getsessionIddata() {
				this.sessionIddata = localStorage.getItem('sessionId');
				this.storeCodedata = localStorage.getItem('storeCode')
			},
			//获取首页可领的优惠券
			queryCoupons() {
				let url = api.base_host + '/advConfig/findOnDisplay'
				let config = {
					url: url,
					method: 'GET',
					params: {
						enterpriseCode: api.enterpriseCode,
						storeCode: this.storeCodedata,
					},
					headers: {
						'sessionId': this.sessionIddata,
					},
				};
				axios(config).then((res) => {
					let arreydata = res.data.data
					if(arreydata.length > 0) {
						for(var i = 0; i < arreydata.length; i++) {
							if(arreydata[i].storeCode == this.storeCodedata && arreydata[i].advKind === 1 && !this.sessionIddata || arreydata[i].storeCode == this.storeCodedata && arreydata[i].advKind === 1 && this.sessionIddata == undefined) {
								this.advImg = arreydata[i].advImg
								this.advLink = arreydata[i].advLink
								this.adType = arreydata[i].advKind
							} else if(arreydata[i].storeCode == this.storeCodedata && arreydata[i].advKind === 3 && this.sessionIddata || arreydata[i].storeCode == this.storeCodedata && arreydata[i].advKind === 3 && this.sessionIddata != undefined) {
								this.couponsdata = arreydata[i].couponList
							}else if(arreydata[i].storeCode == this.storeCodedata && arreydata[i].advKind === 2 && this.sessionIddata || arreydata[i].storeCode == this.storeCodedata && arreydata[i].advKind === 2 && this.sessionIddata != undefined) {
								this.advImg = arreydata[i].advImg
								this.advLink = arreydata[i].advLink
								this.adType = arreydata[i].advKind
							} 
						}
						if(this.page == "home") {
							this.setpopupVisible(true)
							this.setactivePic([this.advImg, this.advLink, this.adType, this.couponsdata])
						}
					}
				})
			},
			//初始化监听门店数据变化
			initListenerForStoreCodeChange() {
				PSEvent.listen("changeStoreCode", () => {
					this.getsessionIddata()
				    this.getHomeData(true);
				});
			},
			removeListen() {
				PSEvent.remove("changeStoreCode");
				PSEvent.remove("dataRefresh", this.dataRefresh);
			},
			//请求首页模板配置的数据
			getHomeData(isRefresh = false){
				initData(isRefresh);
			}
		},
		beforeCreate() {
			var index = this.$route.query.pageIndex ?
				parseInt(this.$route.query.pageIndex) :
				0;
			this.$store.dispatch("cjy/changeClassifyIndex", index);
		},
		created() {
			this.getsessionIddata();
			if(!this.$store.state.xxy.hasNotice) {
				this.queryCoupons()
			}
			this.getHomeData();
			window.PSEvent.listen('dataRefresh', this.dataRefresh);
			setTimeout(()=>{
				this.flagfoot = true;
				this.refresh();
			}, 1500);
			//初始化门店code变化时的监听，以便于重新请求首页数据
			this.initListenerForStoreCodeChange();
		},
		mounted() {
			
		},
		updated() {
			//页面更新完毕
			this.$nextTick(() => {
				this.refresh()
			});
		},
		beforeDestroy() {
			// console.log("beforeDestroy---beforeDestroy");
			
			this.$refs.classifyList && this.$refs.classifyList[0] && this.$refs.classifyList[0].savePageNum();
			this.$store.commit("cjy/SET_IS_RETURN", false);
			this.removeListen();
		},
		watch: {
			scrollTop(newdata, olddata) {
				if(newdata < 10) {
					this.sethomehid(true);
				}
				if(parseInt(newdata) - parseInt(olddata) < -6) {
					this.sethomehid(true);
				} else if(parseInt(newdata) - parseInt(olddata) > 6) {
					this.sethomehid(false);
				}
			},
			hasNotice(data) {
				if(!data) {
					this.queryCoupons()
				}
			}
		},
		beforeRouteLeave(to, from, next) {
			this.pageState = "hide";
			var name = from.name
			this.$store.commit("cjy/SET_IS_RETURN", false);
			this.$store.commit('cjy/SET_RETURN_POS', name)
			next()
		},
	};
</script>

<style scoped>
	.outer-box {
		display: block;
		width: 100%;
		height: 100%;
		padding-top: 2.5rem;
		position: relative;
		flex-flow: column nowrap;
		justify-content: space-between;
	}
	
	.main-container {
		width: 100%;
		height: 100%;
		position: absolute;
		top: 0;
		overflow-y: scroll;
		overflow-x: hidden;
		/*-webkit-overflow-scrolling : touch;*/
	}
	
	.coupons {
		position: fixed;
		top: 18rem;
		right: 0rem;
		max-width: 30%;
		z-index: 1;
	}
	
	.coupons_cloce {
		position: absolute;
		right: 0px;
		top: 0px;
		max-width: 18%;
	}
</style>